﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Blazing.BusinessObjects.Cms;
using System.Web.Configuration;

namespace Blazing.WebFacade.Extensions
{
    public static class SiteUtilExtensions
    {
        public static Site GetSite(this Uri uri)
        {
            string hostUrl = uri.Host;
            try
            {
                //if test app
                if (WebConfigurationManager.AppSettings["TestMode"] == "True")
                    hostUrl = WebConfigurationManager.AppSettings["TestSite"];

                return new SiteController().GetSite(hostUrl);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("Failed to find site record for {0}.", hostUrl), ex);
            }
        }

        /// <summary>
        /// Returns the current cms page that exists at the current url
        /// </summary>
        public static Contentpage GetCurrentPage(this Uri uri)
        {
            Site _site = uri.GetSite();
            Contentpage _page = null;
            if (_site != null)
            {
                string requestUrl = uri.PathAndQuery;
                requestUrl = requestUrl ?? string.Empty;
                requestUrl = string.Format("{0}{1}", requestUrl.StartsWith("/") ? "" : "/", requestUrl);
                requestUrl = requestUrl.Replace(".aspx", "");
                requestUrl = string.Format("{0}{1}", requestUrl, requestUrl.EndsWith("/") ? "" : "/");

                PageController pageCon = new PageController();
                _page = pageCon.GetPage(_site.ID, requestUrl);
            }

            return _page;
        }
    }
}
